package com.example.shiyansan.service.impl;


import com.example.shiyansan.dto.UserLoginDTO;
import com.example.shiyansan.entity.User;
import com.example.shiyansan.mapper.UserMapper;
import com.example.shiyansan.service.UserService;
import com.example.shiyansan.utils.JwtUtil;
import com.example.shiyansan.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户登录
     * @param userLoginDTO
     */
    @Transactional
    @Override
    public UserLoginVo findByUsernameAndPassword(UserLoginDTO userLoginDTO) throws Exception {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //判断数据库中有没有这个人
        User user = userMapper.findByUsername(username);

        if(user == null){
            //TODO 后期改成全局异常处理
            throw new Exception("用户不存在");
        }
        //判断密码是否正确
        if(!user.getPassword().equals(password)){
            throw new Exception("用户密码错误");
        }
//        生成token令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId",user.getUserId());
        String token = JwtUtil.createJWT(claims);
        stringRedisTemplate.opsForValue().set("user:token:"+user.getUserId(),token,7200000, TimeUnit.SECONDS);
//        返回userLoginVo，放入token，便于前端进行校验
        UserLoginVo userLoginVo = UserLoginVo.builder()
                .userId(user.getUserId())
                .token(token)
                .username(user.getUsername())
                .password(user.getPassword())
                .email(user.getEmail()).build();

        return userLoginVo;
    }

    @Transactional
    @Override
    public void register(User user) throws Exception {
        //TODO 应该在用户输入信息的时候就判断用户是否存在
        //首先判断该用户是否存在
        User user1 = userMapper.findByUsername(user.getUsername());
        if(user1 != null){
            throw new Exception("该用户已存在");
        }
        //根据提交的信息然后在数据库中插入数据
        userMapper.insertUser(user);
    }
}
